package com.situ.home;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TestServlet
 */
public class TestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 记录当前访问时间，设置到cookie上
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String time = simpleDateFormat.format(date);
		System.out.println(time);
		// bug在25行-33行之间 空指针异常 cookie有值但好像没有传递？
		Cookie cookie = new Cookie("lastAccessTime", time);
		System.out.println(cookie);
		resp.addCookie(cookie);

		// 获得cookie ，显示到页面上
		String lastAccessTime = null;
		Cookie[] cookies = req.getCookies();
		System.out.println(cookies);
		if (cookies != null) {
			for (Cookie cookie2 : cookies) {
				if (cookie2.getName().equals(lastAccessTime)) {
					lastAccessTime = cookie2.getValue();
				}
			}
		}
		// 显示到页面上
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		if (lastAccessTime == null) {
			writer.println("您是第一次访问");
		} else {
			writer.print("您上次访问的时间为" + lastAccessTime);
		}
	}
}
